<?php

class Admin_Table_Regions extends Apk_Db_Table
{
	protected $_name      = 'regions';
    protected $_primary   = 'id';
    protected $_ERROR = '';    
    protected $_lang;
    
    public function __construct($lang = 'ru')
    {
    	$this->_lang = $lang;
    	parent::__construct();
    }    

    public function GetError()
    {
    	return $this->_ERROR;
    } 
    
    public function GetDataList($page = 1, $sort=null, $page_count=null)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from($this->_name, array('id', 'name' => 'name_'.$this->_lang))
    		  ->joinLeft('countries', 'countries.id = regions.id_country', array('country' => 'name_'.$this->_lang));    		  
    		  
		if(!is_null($sort) && strlen($sort) > 0) 
		{			
			$sel->order($sort);			
		}
		else $sel->order($this->_name.'.name_'.$this->_lang);  		
		

    	return $this->setDecorator('simpleDecorator')->getPager($sel, $page, array('perPage' => $page_count));
    } 
    
    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
    				->where('id = ?', $id);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->getRow(0)->toArray();
    }      


	public function insert(array $data)
    {
        $data['name_ru'] = trim($data['name_ru']);
        if($data['name_ru'] == ''){
        	$this->_ERROR = 'Необходимо ввести Название';
        	return false;
        }

        return parent::insert($data);		
    }

    public function update(array $data, $id)
    {
        $data['name_ru'] = trim($data['name_ru']);
        if($data['name_ru'] == ''){
        	$this->_ERROR = 'Необходимо ввести Название';
        	return false;
        }

		return parent::update($data, 'id = '.$id);
    }

    public function remove($items)
    {
    	foreach($items as $k => $id)
    	{	    	
	    	$this->getAdapter()->delete('cities', 'id_region = '.$id);
    		parent::delete('id = '.$id);
    	}    	
    	return true;
	}


    /********************
     ***  Decorators  ***
    *********************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);            	
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

}
?>